<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
    />
    <Editor
      style="height: 500px; overflow-y: hidden"
      v-model="valueHtmls"
      :defaultConfig="editorConfig"
      @onChange="submitContent"
      @onCreated="handleCreated"
    />
  </div>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted, onUnmounted } from 'vue'
import { BASE_URLS } from '@/api/config.js'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import emitter from '@/utils/eventbus.js'

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const props = defineProps(['valueHtml'])

const valueHtmls = ref('')

onMounted(() => {
  setTimeout(() => {
    valueHtmls.value = props.valueHtml
  }, 250)
})

const submitContent = () => {
  // valueHtmls.value = props.valueHtml
}

defineExpose({ valueHtmls })

const editorConfig = { MENU_CONF: {} }
const toolbarConfig = {}
// 页面回显内容
editorConfig.placeholder = '请输入'
// 上传图片
editorConfig.MENU_CONF['uploadImage'] = {
  server: BASE_URLS + '/api/changan/upload/picture',
  fieldName: 'picture',
  meta: {
    token: localStorage.getItem('token'),
    otherKey: 'Bearer Token'
  },
  maxFileSize: 100 * 1024 * 1024,
  maxNumberOfFiles: 9,
  customInsert(res, insertFn) {
    let url = BASE_URLS + `/api/changan/moment/images/${res[0]}`
    insertFn(url, '', '')
  }
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

onUnmounted(() => {
  emitter.off('productContentChange')
})
</script>

<style lang="scss" scoped></style>
